// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129

const appId = "41222117"
const appKey = "Kg4LZew8vhXTWSTNuvtyG6S3"
const secretKey = "KvUPzoMtYysyYxYbVASptYmq67xSGqwu"
const mediaManager = uniCloud.ai.getMediaManager({
	provider: 'baidu',
	accessToken: '2592000 24.b58e467bdc064a94dfea2b3f3fa485e7.2592000.1700120486.282335-41222117'
})

// 引入uniCloud.database()方法，并创建db对象
const db = uniCloud.database();
// 创建userscollection对象
const userscollection = db.collection('uni-id-users')
//积分记录
const userscores = db.collection("uni-id-scores")
// 引入uni-id-common模块
const uniIdCommon = require('uni-id-common')
// const db = uniCloud.database();
module.exports = {

	_before: async function() {
		const url =
			`https://aip.baidubce.com/oauth/2.0/token?client_id=${appKey}&client_secret=${secretKey}&grant_type=client_credentials`
		/*先校验token（用户身份令牌）是否有效，并获得用户的_id*/
		// 获取客户端信息
			// console.log("0000000000000-----")
		if (this.getHttpInfo().body) {
			
			this.clientInfo = this.getClientInfo()
			let body = JSON.parse(this.getHttpInfo().body)
			this.clientInfo = {
				...this.clientInfo,
				...body.clientInfo

			}
			this.body = body
			// console.log("0000000000000",this.body)
			const spentScore = 1000 //销毁积分
			if (this.getMethodName() == 'imageGeneration') {
				// console.log("11111111")
				// 定义uni-id公共模块对象
				this.uniIdCommon = uniIdCommon.createInstance({
					clientInfo: this.clientInfo
				})
				// 校验token（用户身份令牌）是否有效，并获得用户的_id
				let res = await this.uniIdCommon.checkToken(this.clientInfo.uniIdToken)
				if (res.errCode) {
					// 如果token校验出错，则抛出错误
					throw res
				} else {
					// 通过token校验则，拿去用户id
					this.current_uid = res.uid
				}
				/* 判断剩余多少积分：拒绝对话、扣除配置的积分数 */
				let {
					data: [{
						score
					}]
				} = await userscollection.doc(this.current_uid).field({
					'score': 1
				}).get()
				// 如果积分余额小于与uni-ai对话一次所需消耗的积分数 即 积分不足 则抛出错误提醒客户端
				if (score < spentScore) {
					throw "insufficientScore"
				}
				// 扣除对应的积分值
				await userscollection.doc(this.current_uid)
					.update({
						score: db.command.inc(-1 * spentScore)
					})
				//记录扣除积分
				await userscores.add({
					user_id: this.current_uid,
					score: spentScore,
					type: 2,
					balance: score - spentScore
				})

			}


		}


	},
	/**
	 * method1方法描述
	 * @param {string} param1 参数1描述
	 * @returns {object} 返回值描述
	 */
	async imageGeneration() {
		// console.log("222222222222",this.body.params)
		if (!this.body.params) {
			return {
				code: 1,
				msg: 'prams参数错误'
			}
		}
		const params = this.body.params

		if (!params.prompt) return {
			code: 1,
			message: "prompt必填"
		}
		const res = await mediaManager.imageGeneration({
			version: 1,
			prompt: params.prompt,
			style: params.style || '探索无限',
			resolution: params.resolution || '1024*1024',
			imageNum: params.imageNum || 1,

		})
		const taskId = res.taskId

		return {
			task_id: taskId
		}
	},
	async getGeneratedImage() {
		if (!this.body.params) {
			return {
				code: 1,
				msg: 'prams参数错误'
			}
		}
		const params = this.body.params
		const res = await mediaManager.getGeneratedImage({
			version: params.version,
			taskId: params.task_id
		})
		return {
			imgList: res.imgList
		};

	}




}